package com.leosam.tvbox.mv.data;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.leosam.tvbox.mv.proxy.M3u8Media;
import com.leosam.tvbox.mv.service.MvService;
import com.leosam.tvbox.mv.utils.VertxUtils;

public class VodSeries {

    @JsonIgnore
    private Vod vod;

    /**
     * 集名
     */
    private String seriesName;

    /**
     * 目标文件名
     */
    private String fileName;

    /**
     * 原始uri
     */
    private String originUrl;

    /**
     * 已缓存
     */
    private boolean cached;

    public Vod getVod() {
        return vod;
    }

    public void setVod(Vod vod) {
        this.vod = vod;
    }

    public String getSeriesName() {
        return seriesName;
    }

    public void setSeriesName(String seriesName) {
        this.seriesName = seriesName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getOriginUrl() {
        return originUrl;
    }

    public void setOriginUrl(String originUrl) {
        this.originUrl = originUrl;
    }

    public boolean isCached() {
        return cached;
    }

    public void setCached(boolean cached) {
        this.cached = cached;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(seriesName);

        if (fileName.equals(M3u8Media.NAME_INDEX_M3U8)) {
            try {
                sb.append("$").append(VertxUtils.getProxyUrl()).append("/")
                        .append(URLEncoder.encode(vod.getVodName(), "UTF-8")).append("/")
                        .append(URLEncoder.encode(seriesName, "UTF-8")).append("/").append("index.m3u8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            if (!cached) {
                Path path = Paths.get(MvService.DATA_PATH, MvService.MEDIA_PATH, vod.getCachePath(), "/", fileName);
                if (path.toFile().exists()) {
                    cached = true;
                }
            }
            if (cached) {
                sb.append("$").append(VertxUtils.getMediaUrl()).append("/").append(vod.getCachePath()).append("/")
                        .append(fileName);
            } else {
                sb.append("-未缓存$").append(originUrl);
            }
        }

        return sb.toString();
    }

}
